//
//  ATDrawTrackManager.m
//  ATGaode_demo
//
//  Created by Chengquan Ye on 2019/3/8.
//  Copyright © 2019年 Chengquan Ye. All rights reserved.
//

#import "ATDrawTrackManager.h"
#import <SVProgressHUD.h>

@interface ATDrawTrackManager () <AMapTrackManagerDelegate>

/** trackManager */
@property (nonatomic, strong) AMapTrackManager *trackManager;

@end

@implementation ATDrawTrackManager

+ (instancetype)manager
{
    return [[ATDrawTrackManager alloc] init];;
}

- (instancetype)init
{
    if (self = [super init]) {
        _pageSize = 20;
        self.pageIndex = 1;
        self.cacheMaxSize = 50;
        self.gatherInterval = 2; // 2秒采集一次
        self.packInterval = 20; // 20秒上传一次
    }
    return self;
}

- (void)setupTrackManager:(NSString *)serviceID
{
    NSAssert(serviceID != nil, @"serviceID一定要传");
    
    _serviceID = serviceID;
    
    AMapTrackManagerOptions *option = [[AMapTrackManagerOptions alloc] init];
    option.serviceID = serviceID; //Service ID 需要根据需要进行修改
    
    //初始化AMapTrackManager
    self.trackManager = [[AMapTrackManager alloc] initWithOptions:option];
    self.trackManager.delegate = self;
    
    // a.配置定位属性
    [self.trackManager setAllowsBackgroundLocationUpdates:YES];
    [self.trackManager setPausesLocationUpdatesAutomatically:NO];
    
    // b.配置定位采集周期和上报周期
    [self.trackManager changeGatherAndPackTimeInterval:self.gatherInterval packTimeInterval:self.packInterval];
    
    // c.配置本地缓存大小
    [self.trackManager setLocalCacheMaxSize:self.cacheMaxSize];
}

/** 开启服务 */
- (void)startServiceWithTerminalName:(NSString *)terminalName;
{
    NSAssert(terminalName != nil, @"terminalName不能为空");
    
    _terminalName = terminalName;
    
    // 查询终端是否存在
    [self queryTerminalIsExist:terminalName];
}

/** 正式开始服务 */
- (void)startServiceNow
{
    // 开始服务
    AMapTrackManagerServiceOption *serviceOption = [[AMapTrackManagerServiceOption alloc] init];
    serviceOption.terminalID = self.terminalID;//Terminal ID 需要根据需要进行修改
    [self.trackManager startServiceWithOptions:serviceOption];
}

/** 结束服务 */
- (void)stopService
{
    [self.trackManager stopService];
}

/** 开始采集和上传 */
- (void)startGather
{
    if (self.trackID) {
        self.trackManager.trackID = self.trackID;
    }
    [self.trackManager startGatherAndPack];
}

/** 结束采集 */
- (void)stopGather
{
    [self.trackManager stopGaterAndPack];
}

/** 查询终端是否存在 */
- (void)queryTerminalIsExist:(NSString *)terminalName
{
    // 查询终端是否存在
    AMapTrackQueryTerminalRequest *request = [[AMapTrackQueryTerminalRequest alloc] init];
    request.serviceID = self.serviceID;
    request.terminalName = terminalName;
    [self.trackManager AMapTrackQueryTerminal:request];
}

#pragma mark - 查询终端结果
//查询终端结果
- (void)onQueryTerminalDone:(AMapTrackQueryTerminalRequest *)request response:(AMapTrackQueryTerminalResponse *)response
{
    //查询成功
    if ([[response terminals] count] > 0) {
        //查询到结果，使用 Terminal ID
        NSString *terminalID = [[[response terminals] firstObject] tid];
        
        _terminalID = terminalID;
        
        // 开启服务
        [self startServiceNow];
    }
    else {
        // 查询结果为空，创建新的terminal
        AMapTrackAddTerminalRequest *addRequest = [[AMapTrackAddTerminalRequest alloc] init];
        addRequest.serviceID = self.serviceID;
        addRequest.terminalName = self.terminalName;
        [self.trackManager AMapTrackAddTerminal:addRequest];
    }
}

#pragma mark - 创建终端结果
//创建终端结果
- (void)onAddTerminalDone:(AMapTrackAddTerminalRequest *)request response:(AMapTrackAddTerminalResponse *)response {
    //创建terminal成功
    NSString *terminalID = [response terminalID];
    
    //启动上报服务(service id)，参考下一步
    NSLog(@"创建终端成功=---terminalID = %@", terminalID);
    _terminalID = terminalID;
    
    if (response.code == AMapTrackErrorOK) {
        
        // 开启服务
        [self startServiceNow];
    }
}

#pragma mark - 创建轨迹
/** 创建轨迹 */
- (void)doCreateTrackName {
    if (self.trackManager == nil) {
        return;
    }
    
    AMapTrackAddTrackRequest *request = [[AMapTrackAddTrackRequest alloc] init];
    request.serviceID = self.serviceID;
    request.terminalID = self.terminalID;
    [self.trackManager AMapTrackAddTrack:request];
}

#pragma mark - 查询最后一个位置点
- (void)queryLastestPoint
{
    AMapTrackQueryLastPointRequest *request = [[AMapTrackQueryLastPointRequest alloc] init];
    request.serviceID = self.serviceID;
    request.terminalID = self.terminalID;
//    request.correctionMode = @"driving";
    [self.trackManager AMapTrackQueryLastPoint:request];
}

#pragma mark - 查询轨迹行驶距离接口
- (void)queryTrackDistance:(AMapTrackQueryTrackDistanceRequest *)request
{
    [self.trackManager AMapTrackQueryTrackDistance:request];
}

#pragma mark - 查询轨迹历史数据和行驶距离接口
- (void)queryTrackHistoryAndDistance:(AMapTrackQueryTrackHistoryAndDistanceRequest *)request
{
    [self.trackManager AMapTrackQueryTrackHistoryAndDistance:request];
}

#pragma mark - 查询轨迹历史数据
- (void)queryTrackInfo:(AMapTrackQueryTrackInfoRequest *)request
{
    [self.trackManager AMapTrackQueryTrackInfo:request];
}

#pragma mark - 开启服务回调
- (void)onStartService:(AMapTrackErrorCode)errorCode {
    NSLog(@"开始服务:%zd", errorCode);
    if (errorCode == AMapTrackErrorOK) {
        //开始服务成功，继续开启收集上报
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(startServiceIsSuccess:)]) {
            [self.delegate startServiceIsSuccess:YES];
        }
        
        if (self.isUploadAllPoint) {
            // 2种: 先采集，不创建轨迹，散点轨迹
            [self.trackManager startGatherAndPack];
        } else {
            // 1种: 先创建轨迹再采集
            [self doCreateTrackName];
        }
    } else {
        //开始服务失败
        if (self.delegate && [self.delegate respondsToSelector:@selector(startServiceIsSuccess:)]) {
            [self.delegate startServiceIsSuccess:NO];
        }
    }
}

#pragma mark - 结束服务回调
- (void)onStopService:(AMapTrackErrorCode)errorCode
{
    NSLog(@"结束服务:%zd", errorCode);
    if (errorCode == AMapTrackErrorOK) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(stopServiceIsSuccess:)]) {
            [self.delegate stopServiceIsSuccess:YES];
        }
    } else {
        //开始服务失败
        if (self.delegate && [self.delegate respondsToSelector:@selector(stopServiceIsSuccess:)]) {
            [self.delegate stopServiceIsSuccess:NO];
        }
    }
}

#pragma mark - 开启采集结果回调
- (void)onStartGatherAndPack:(AMapTrackErrorCode)errorCode {
    NSLog(@"开始采集:%zd", errorCode);
    if (errorCode == AMapTrackErrorOK) {
        //开始采集成功
        if (self.delegate && [self.delegate respondsToSelector:@selector(startGatherAndPackIsSuccess:)]) {
            [self.delegate startGatherAndPackIsSuccess:YES];
        }
    } else {
        //开始采集失败
        if (self.delegate && [self.delegate respondsToSelector:@selector(startGatherAndPackIsSuccess:)]) {
            [self.delegate startGatherAndPackIsSuccess:NO];
        }
    }
}

#pragma mark - 结束采集结果回调
- (void)onStopGatherAndPack:(AMapTrackErrorCode)errorCode {
    
    NSLog(@"结束采集:%ld", (long)errorCode);
    
    if (errorCode == AMapTrackErrorOK) { //
        //结束采集成功
        if (self.delegate && [self.delegate respondsToSelector:@selector(stopGatherAndPackIsSuccess:)]) {
            [self.delegate stopGatherAndPackIsSuccess:YES];
        }
    } else {
        //结束采集失败
        if (self.delegate && [self.delegate respondsToSelector:@selector(stopGatherAndPackIsSuccess:)]) {
            [self.delegate stopGatherAndPackIsSuccess:NO];
        }
    }
}

#pragma mark - 创建轨迹回调
- (void)onAddTrackDone:(AMapTrackAddTrackRequest *)request response:(AMapTrackAddTrackResponse *)response
{
    //创建轨迹成功，开始采集
    _trackID = response.trackID;
    NSLog(@"轨迹id =-== %@", response.trackID);
    
    if (response.code == AMapTrackErrorOK) {
        self.trackManager.trackID = _trackID;
        [self.trackManager startGatherAndPack];
    } else {
        
    }
}


#pragma mark - 错误回调
- (void)didFailWithError:(NSError *)error associatedRequest:(id)request {
    NSLog(@"错误回调 ======== %@", error);
    if ([request isKindOfClass:[AMapTrackQueryTerminalRequest class]]) {
        //查询参数错误
        NSLog(@"查询参数错误");
    }
    
    if ([request isKindOfClass:[AMapTrackAddTerminalRequest class]]) {
        //创建terminal失败
        NSLog(@"创建terminal失败");
    }
    
    if ([request isKindOfClass:[AMapTrackAddTrackRequest class]]) {
        //创建轨迹失败
        NSLog(@"创建轨迹失败");
    }
    
    if ([request isKindOfClass:[AMapTrackQueryLastPointRequest class]]) {
        //查询失败
        NSLog(@"查询实时点失败");
    }
    
    if ([request isKindOfClass:[AMapTrackQueryTrackInfoRequest class]]) {
        NSLog(@"查询历史轨迹点失败");
    }
    
    if ([request isKindOfClass:[AMapTrackQueryTrackDistanceRequest class]]) {
        NSLog(@"查询历史轨迹里程失败");
    }
    
    if ([request isKindOfClass:[AMapTrackQueryTrackHistoryAndDistanceRequest class]]) {
        NSLog(@"查询历史轨迹点和里程失败");
    }
}

#pragma mark - 查询最后一个位置点的回调
- (void)onQueryLastPointDone:(AMapTrackQueryLastPointRequest *)request response:(AMapTrackQueryLastPointResponse *)response
{
    //查询成功
//    NSLog(@"onQueryLastPointDone====%f=====%f===%f", response.lastPoint.coordinate.latitude, response.lastPoint.coordinate.longitude, response.lastPoint.accuracy);
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(queryLastPointDone:response:)]) {
        [self.delegate queryLastPointDone:request response:response];
    }
}

#pragma mark - 查询轨迹历史数据回调函数
- (void)queryTrackInfoDone:(AMapTrackQueryTrackInfoRequest *)request response:(AMapTrackQueryTrackInfoResponse *)response
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(queryTrackInfoDone:response:)]) {
        [self.delegate queryTrackInfoDone:request response:response];
    }
}

#pragma mark - 查询轨迹历史数据和行驶距离回调函数
- (void)queryTrackHistoryAndDistanceDone:(AMapTrackQueryTrackHistoryAndDistanceRequest *)request response:(AMapTrackQueryTrackHistoryAndDistanceResponse *)response
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(queryTrackHistoryAndDistanceDone:response:)]) {
        [self.delegate queryTrackHistoryAndDistanceDone:request response:response];
    }
}

#pragma mark - 查询轨迹行驶距离回调函数
- (void)queryTrackDistanceDone:(AMapTrackQueryTrackDistanceRequest *)request response:(AMapTrackQueryTrackDistanceResponse *)response
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(queryTrackDistanceDone:response:)]) {
        [self.delegate queryTrackDistanceDone:request response:response];
    }
}

/** 界面销毁处理 */
- (void)deallocDoSomething
{
    [self.trackManager stopGaterAndPack];
    [self.trackManager stopService];
    self.trackManager.delegate = nil;
    self.trackManager = nil;
}

@end
